package com.mike.uaa;

import com.mike.uaa.web.ApplicationContextUtils;
import com.mike.uaa.web.AuthenticationInterceptor;
import com.mike.uaa.web.redis.AuthenticationRepository;
import com.mike.uaa.web.redis.AuthenticationRepositoryImpl;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author z
 */
@Configuration
public class UaaWebFilterAutoConfiguration implements WebMvcConfigurer, ApplicationContextAware {

    @Bean
    public RedisOperations<String, Object> defaultRedisOps(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        return template;
    }

    @Bean
    public AuthenticationRepository authenticationRepository(RedisConnectionFactory connectionFactory) {
        return new AuthenticationRepositoryImpl(defaultRedisOps(connectionFactory));
    }

    @Bean
    public AuthenticationInterceptor authenticationInterceptor(AuthenticationRepository authenticationRepository) {
        return new AuthenticationInterceptor(authenticationRepository);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 直接调用 @Bean 方法获取拦截器实例
        AuthenticationInterceptor interceptor = ApplicationContextUtils.getBean(AuthenticationInterceptor.class);
        registry.addInterceptor(interceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login",                   // 登录页面
                        "/logout",                  // 退出登录
                        "/static/**",               // 静态资源
                        "/error"                    // 错误页面
                );
        ;
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        ApplicationContextUtils.setApplicationContext(context);
    }
}
